"""
WebSocket通知工具 - 提供便捷的消息推送函数
支持多种业务场景：订单、支付、收藏、评价、系统消息等
"""
import json
import logging
from datetime import datetime
from typing import Optional, Dict, Any
from utils.redis_utils import get_redis

logger = logging.getLogger(__name__)


def send_ws_notification(
    user_id: int,
    notification_type: str,
    title: str,
    message: str,
    data: Optional[Dict[str, Any]] = None,
    priority: str = "normal"
):
    """
    发送WebSocket通知到指定用户
    
    Args:
        user_id: 用户ID
        notification_type: 通知类型（order, payment, favorite, review, system, verify_result等）
        title: 通知标题
        message: 通知消息内容
        data: 附加数据（可选）
        priority: 优先级（low, normal, high, urgent）
    
    Examples:
        # 订单状态变化通知
        send_ws_notification(
            user_id=123,
            notification_type="order",
            title="订单状态更新",
            message="您的订单 #ORD123456 已支付成功",
            data={"order_id": 123, "order_no": "ORD123456", "status": "paid"}
        )
        
        # 支付成功通知
        send_ws_notification(
            user_id=123,
            notification_type="payment",
            title="支付成功",
            message="您已成功支付 ¥299.00",
            data={"order_id": 123, "amount": 299.00}
        )
    """
    redis_client = get_redis()
    notification = {
        "type": notification_type,
        "title": title,
        "message": message,
        "data": data or {},
        "priority": priority,
        "timestamp": datetime.now().isoformat()
    }
    
    try:
        # 将通知放入Redis列表，供WebSocket服务读取
        redis_client.lpush(f"ws_notifications:{user_id}", json.dumps(notification))
        redis_client.expire(f"ws_notifications:{user_id}", 86400)  # 24小时过期
        logger.info(f"已发送通知到用户 {user_id}: {notification_type} - {title}")
    except Exception as e:
        logger.error(f"发送通知失败: {e}", exc_info=True)


def notify_order_status_change(user_id: int, order_id: int, order_no: str, old_status: str, new_status: str, amount: float = None):
    """订单状态变化通知"""
    status_map = {
        "pending": "待支付",
        "paid": "已支付",
        "completed": "已完成",
        "cancelled": "已取消",
        "refunding": "退款中",
        "refunded": "已退款"
    }
    
    title = "订单状态更新"
    message = f"您的订单 #{order_no} 状态已更新：{status_map.get(old_status, old_status)} → {status_map.get(new_status, new_status)}"
    
    send_ws_notification(
        user_id=user_id,
        notification_type="order",
        title=title,
        message=message,
        data={
            "order_id": order_id,
            "order_no": order_no,
            "old_status": old_status,
            "new_status": new_status,
            "amount": amount
        },
        priority="high" if new_status in ["paid", "completed"] else "normal"
    )


def notify_payment_success(user_id: int, order_id: int, order_no: str, amount: float, payment_method: str = "支付宝"):
    """支付成功通知"""
    send_ws_notification(
        user_id=user_id,
        notification_type="payment",
        title="支付成功",
        message=f"您已成功支付 ¥{amount:.2f}，订单 #{order_no}",
        data={
            "order_id": order_id,
            "order_no": order_no,
            "amount": amount,
            "payment_method": payment_method
        },
        priority="high"
    )


def notify_payment_failed(user_id: int, order_id: int, order_no: str, reason: str = "支付失败"):
    """支付失败通知"""
    send_ws_notification(
        user_id=user_id,
        notification_type="payment",
        title="支付失败",
        message=f"订单 #{order_no} 支付失败：{reason}",
        data={
            "order_id": order_id,
            "order_no": order_no,
            "reason": reason
        },
        priority="urgent"
    )


def notify_favorite_added(user_id: int, attraction_id: int, attraction_name: str):
    """收藏成功通知"""
    send_ws_notification(
        user_id=user_id,
        notification_type="favorite",
        title="收藏成功",
        message=f"您已收藏了「{attraction_name}」",
        data={
            "attraction_id": attraction_id,
            "attraction_name": attraction_name,
            "action": "added"
        },
        priority="low"
    )


def notify_favorite_removed(user_id: int, attraction_id: int, attraction_name: str):
    """取消收藏通知"""
    send_ws_notification(
        user_id=user_id,
        notification_type="favorite",
        title="取消收藏",
        message=f"您已取消收藏「{attraction_name}」",
        data={
            "attraction_id": attraction_id,
            "attraction_name": attraction_name,
            "action": "removed"
        },
        priority="low"
    )


def notify_review_added(user_id: int, attraction_id: int, attraction_name: str, review_id: int, rating: float):
    """新增评价通知（通知景点所有者或管理员）"""
    send_ws_notification(
        user_id=user_id,  # 这里可以是景点所有者ID或管理员ID
        notification_type="review",
        title="收到新评价",
        message=f"「{attraction_name}」收到一条新评价（{rating}分）",
        data={
            "attraction_id": attraction_id,
            "attraction_name": attraction_name,
            "review_id": review_id,
            "rating": rating
        },
        priority="normal"
    )


def notify_review_replied(user_id: int, review_id: int, attraction_name: str):
    """评价被回复通知"""
    send_ws_notification(
        user_id=user_id,
        notification_type="review",
        title="评价收到回复",
        message=f"您对「{attraction_name}」的评价收到回复",
        data={
            "review_id": review_id,
            "attraction_name": attraction_name,
            "action": "replied"
        },
        priority="normal"
    )


def notify_system_message(user_id: int, title: str, message: str, data: Optional[Dict[str, Any]] = None):
    """系统消息通知"""
    send_ws_notification(
        user_id=user_id,
        notification_type="system",
        title=title,
        message=message,
        data=data or {},
        priority="normal"
    )


def notify_stock_warning(user_id: int, attraction_id: int, attraction_name: str, remaining_stock: int):
    """库存不足提醒"""
    send_ws_notification(
        user_id=user_id,
        notification_type="stock",
        title="库存提醒",
        message=f"「{attraction_name}」库存仅剩 {remaining_stock} 张，请尽快下单",
        data={
            "attraction_id": attraction_id,
            "attraction_name": attraction_name,
            "remaining_stock": remaining_stock
        },
        priority="high"
    )


def notify_coupon_received(user_id: int, coupon_id: int, coupon_name: str, discount: float):
    """优惠券领取通知"""
    send_ws_notification(
        user_id=user_id,
        notification_type="coupon",
        title="优惠券到账",
        message=f"您获得了一张优惠券：{coupon_name}（¥{discount:.2f}）",
        data={
            "coupon_id": coupon_id,
            "coupon_name": coupon_name,
            "discount": discount
        },
        priority="normal"
    )


def notify_coupon_expiring(user_id: int, coupon_id: int, coupon_name: str, days_left: int):
    """优惠券即将过期提醒"""
    send_ws_notification(
        user_id=user_id,
        notification_type="coupon",
        title="优惠券即将过期",
        message=f"您的优惠券「{coupon_name}」还有 {days_left} 天过期，快来使用吧！",
        data={
            "coupon_id": coupon_id,
            "coupon_name": coupon_name,
            "days_left": days_left
        },
        priority="high"
    )


def notify_verify_result(user_id: int, task_id: str, status: str, message: str, data: Optional[Dict[str, Any]] = None):
    """实名认证结果通知（与ocr_processor.py兼容）"""
    send_ws_notification(
        user_id=user_id,
        notification_type="verify_result",
        title="实名认证结果" if status == "success" else "实名认证失败",
        message=message,
        data=data or {},
        priority="high" if status == "success" else "normal"
    )








